package com.livesource.client.web.projectBacklog.edit;

import java.util.Date;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.livesource.client.LiveSourceGlobalVariables;
import com.livesource.client.model.entry.ProjectClass;
import com.livesource.client.utilities.FileExtensions;
import com.livesource.client.web.projectBacklog.FileNameGenerator;
import com.livesource.client.web.projectBacklog.ProjectBacklogPage;
import com.livesource.client.webservices.RequestSaveLiveFeed;
import com.livesource.client.webservices.subversion.RequestSaveFeature;

/**
 * 
 * @UserInterface
 */
public class ButtonSave extends Button {

	public ButtonSave(final ProjectClass feature) {

		this.setText("Save");

		this.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {

				ProjectClass newFeature = getProjectBacklog(feature);

				LiveSourceGlobalVariables.projectEntries.put(
						newFeature.toString(), newFeature);

				RequestSaveFeature.sendPostRequest(
						LiveSourceGlobalVariables.currentProject
								.getRepositoryURL(), null, null, newFeature);

				RequestSaveLiveFeed.feedUpdateFeature(
						LiveSourceGlobalVariables.userID, newFeature);

				LiveSourceGlobalVariables.showPanel.clear();
				LiveSourceGlobalVariables.showPanel
						.add(new ProjectBacklogPage());
			}
		});
	}

	private ProjectClass getProjectBacklog(final ProjectClass backlogEntry) {

		String featureName = FeatureForm.featureName.getValue();

		backlogEntry.setFeatureName(featureName);

		backlogEntry.setFileExtension(FileExtensions.EXTENSION_FEATURE);

		backlogEntry.setDateModified(new Date());

		String fileName = FileNameGenerator.compactName(featureName) + "."
				+ FileExtensions.EXTENSION_FEATURE;

		backlogEntry.setFileName(fileName);

		backlogEntry.setFilePath(LiveSourceGlobalVariables.featuresPath);

		backlogEntry.setFeatureDescription(FeatureForm.featureDescription
				.getValue());

		if (FeatureForm.featurePriority.getValue() != null
				&& FeatureForm.featurePriority.getValue().length() > 0) {

			backlogEntry.setPriority(new Integer(FeatureForm.featurePriority
					.getValue()));
		}

		if (FeatureForm.featureEstimate.getValue() != null
				&& FeatureForm.featureEstimate.getValue().length() > 0) {

			backlogEntry.setEstimate(new Integer(FeatureForm.featureEstimate
					.getValue()));
		}

		backlogEntry.setStatus(FeatureForm.featureStatus
				.getValue(FeatureForm.featureStatus.getSelectedIndex()));

		return backlogEntry;
	}
}